package cn.tk.service.mr.impl;

import cn.tk.cache.mr.FlowBuf;
import cn.tk.model.entity.mr.FlowNode;
import cn.tk.model.pojo.mr.flow.EntityClarify;
import cn.tk.model.pojo.mr.flow.EntityNodeDTO;
import cn.tk.service.mr.EntityNodeService;
import cn.tk.utils.EmptyUtil;
import cn.tk.utils.JpaMapper;
import cn.tk.utils.RegexUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by denglw on 2021/8/3.<br/>
 * Desc: 实体节点  服务实现层
 */
@Service
public class EntityNodeServiceImpl implements EntityNodeService {

    @Autowired
    private JpaMapper jpaMapper;

    @Override
    public List<EntityNodeDTO> recoverableEntityNodes(Long botId) {
        FlowBuf flowBuf = FlowBuf.getInstance();
        List<FlowNode> flowNodes = flowBuf.botNodes(botId);
        List<Long> ids = flowNodes.stream().filter(i ->
                Objects.equals(i.getType(), 4)).map(FlowNode::getId).collect(Collectors.toList());
        List<EntityNodeDTO> dtos = this.entityNodes(ids);
        // 返回可打断恢复的节点
        return dtos.stream().filter(i -> Objects.equals(i.getRecoverable(), true)).collect(Collectors.toList());
    }

    @Override
    public EntityNodeDTO entityNode(Long entityNodeId) {
        if (EmptyUtil.nullOrZero(entityNodeId)) {
            return null;
        }
        List<EntityNodeDTO> dtos = this.entityNodes(Lists.newArrayList(entityNodeId));
        return EmptyUtil.emptyColl(dtos) ? null : dtos.get(0);
    }

    @Override
    public List<EntityNodeDTO> entityNodes(List<Long> entityNodeIds) {
        List<EntityNodeDTO> dtos = this.baseEntityNodes(entityNodeIds);
        if (EmptyUtil.emptyColl(dtos)) {
            return new ArrayList<>();
        }
        List<EntityClarify> clarifies = this.entityClarifies(entityNodeIds);
        clarifies.stream().collect(Collectors.groupingBy(EntityClarify::getNodeId)).forEach((k ,v) -> {
            for (EntityNodeDTO dto : dtos) {
                boolean match = Objects.equals(dto.getNodeId(), k);
                if (match) {
                    dto.setEntityClarifies(v);
                }
            }
        });
        return dtos;
    }

    private List<EntityNodeDTO> baseEntityNodes(List<Long> nodeIds) {
        String sql = "select a.flow_id flowId, a.id nodeId, b.recoverable, b.appendable\n" +
                "from mr_bot_flow_node a, mr_flow_entity_node b \n" +
                "where a.id=b.id and a.id in (:nodeIds) and a.deleted=0 and a.disabled=0";
        Map<String, Object> params = new HashMap<>(4);
        params.put("nodeIds", nodeIds);
        Class<?>[] clazzes = new Class[]{Long.class, Long.class, Boolean.class, Boolean.class};
        return jpaMapper.queryList(sql, params, EntityNodeDTO.class, clazzes);
    }

    private List<EntityClarify> entityClarifies(List<Long> nodeIds) {
        String sql = "select a.flow_node_id nodeId, a.entity_id entityId, a.necessary,\n" +
                "a.default_entity_value_id defaultEntityValueId, a.clarify_num clarifyNum,\n" +
                "a.bottom_reply_id bottomReplyId, group_concat(concat_ws('@@', b.reply_id, b.sort_num) separator '&&') clarifyReplyTemp\n" +
                "from mr_flow_entity_config a, mr_flow_clarify_reply b where a.id=b.entity_config_id and a.flow_node_id in (:nodeIds) group by a.id";
        Map<String, Object> params = new HashMap<>(4);
        params.put("nodeIds", nodeIds);
        Class<?>[] clazzes = new Class[] {Long.class, Long.class, Boolean.class, Long.class, Integer.class, Long.class, String.class};
        List<EntityClarify> entityClarifies = jpaMapper.queryList(sql, params, EntityClarify.class, clazzes);
        if (EmptyUtil.emptyColl(entityClarifies)) {
            return new ArrayList<>();
        }
        // 解析结果中的澄清话术列表
        for (EntityClarify i : entityClarifies) {
            String clarifyReplyTemp = i.getClarifyReplyTemp();
            if (EmptyUtil.blank(clarifyReplyTemp)) {
                continue;
            }
            // 先按&&分割；再进行@@分割
            String[] rows = clarifyReplyTemp.split("&&");
            if (rows.length == 0) {
                continue;
            }
            List<EntityClarify.ClarifyReply> replies = new ArrayList<>(rows.length);
            for (String row : rows) {
                String[] items = row.split("@@");
                if (items.length != 2) {
                    continue;
                }
                String item1 = items[0];
                String item2 = items[1];
                boolean matchReplyId = RegexUtil.isMatch(RegexUtil.NUMBER, item1);
                boolean matchSortNum = RegexUtil.isMatch(RegexUtil.NUMBER, item2);
                if (!matchReplyId ||!matchSortNum) {
                    continue;
                }
                long replyId = Long.parseLong(item1);
                int sortNum = Integer.parseInt(item2);
                replies.add(new EntityClarify.ClarifyReply(replyId, sortNum));
            }
            i.setClarifyReplies(replies);
        }
        return entityClarifies;
    }

}
